package sourceagile.server.githubFileRepository;

import java.util.List;

import org.codehaus.jettison.json.JSONArray;

import sourceagile.server.subversionFileRepository.ConvertFileToJson;

import com.github.api.v2.schema.Tree;
import com.github.api.v2.schema.Tree.Type;
import com.github.api.v2.services.GitHubServiceFactory;
import com.github.api.v2.services.ObjectService;

public class ListGithubFeatureFiles {

	public static JSONArray listEntries(String username, String projectName,
			String featuresPath) {

		JSONArray entries = new JSONArray();

		GitHubServiceFactory factory = GitHubServiceFactory.newInstance();

		String masterSHA = ListGithubFiles.getMasterRepositorySha(factory,
				username, projectName);

		// service.setAuthentication(new
		// LoginTokenAuthentication("nabeelmukhtar",
		// "xxx-xxx-xxx"));

		ObjectService objectService = factory.createObjectService();

		List<Tree> trees = objectService.getTree(username, projectName,
				masterSHA);

		for (Tree tree : trees) {

			if (Type.BLOB.equals(tree.getType())
					&& tree.getName().startsWith(featuresPath)) {

				entries.put(ConvertFileToJson.convertFromGithub(tree));
			}
		}

		return entries;
	}
}
